import { RbacMenuType } from '@/data/auth/menu';
import { getIcon } from '@/enums/icon';
import AddModal from '@/pages/auth/rbacMenu/components/AddModal';
import UpdateModal from '@/pages/auth/rbacMenu/components/UpdateModal';
import AddButtonTags from '@/pages/auth/rbacMenuTree/components/AddButtonTags';
import AddPermForm from '@/pages/auth/rbacMenuTree/components/AddPermForm';
import { get, list } from '@/services/data';
import { handleAdd, handleUpdate } from '@/services/handle';
import { ActionType, PageContainer, ProCard } from '@ant-design/pro-components';
import { message, Tree, TreeProps } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

const Index: React.FC = () => {
  const [treeData, setTreeData] = useState([]);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<RbacMenuType | null>();
  const [expandedKeys, setExpandedKeys] = useState<any>([]);
  const [checkedKey, setCheckedKey] = useState<any>(null);

  const transformTreeData = (nodes: any[]): any => {
    return nodes.map((node) => {
      // 使用getIcon函数转换图标字符串为组件
      const icon = node.icon ? getIcon(node.icon) : '';

      const children =
        node.children && node.children.length > 0 ? transformTreeData(node.children) : undefined;

      return {
        title: node.title,
        key: node.key,
        icon,
        children,
      };
    });
  };
  useEffect(() => {
    list('/system/rbacMenu/tree').then((data: any) => {
      const transformedData = transformTreeData(data.list);
      setTreeData(transformedData);
      setTimeout(() => {
        setExpandedKeys(['1']);
      }, 0);
    });
  }, []);

  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
    const selectedNode = info.node;

    // 确保节点存在且有key
    if (!selectedNode?.key) {
      setCurrentRow(null);
      setCheckedKey(null);
      return;
    }

    // @ts-ignore
    const isChecked = checkedKeys.checked.includes(selectedNode.key);

    if (isChecked) {
      // 如果勾选当前节点，取消其他节点的勾选状态
      setCheckedKey(selectedNode.key);
      setCurrentRow({ id: selectedNode.key });
    } else {
      // 如果取消勾选当前节点，清空选中状态
      setCheckedKey(null);
      setCurrentRow(null);
    }
  };

  const onSelect: TreeProps['onSelect'] = (checkedKeys, info) => {
    const selectedNode = info.node;

    if (selectedNode) {
      // @ts-ignore
      setCurrentRow({ id: selectedNode.key });
      setCheckedKey(selectedNode.key);
      handleModalVisible(true);
    }
  };

  const onRightClick: TreeProps['onRightClick'] = async (info) => {
    const selectedNode = info.node;
    const id = selectedNode.key;
    // @ts-ignore
    const { data, success } = await get('/system/rbacMenu', id);
    if (!success) {
      message.error('数据不存在');
      return;
    }
    const { name, cnName, icon, path, parentId, sort } = data;
    // @ts-ignore
    setCheckedKey(selectedNode.key);
    setCurrentRow({ id, name, cnName, icon, path, parentId, sort });
    handleUpdateModalVisible(true);
  };
  // @ts-ignore
  const handleExpand = (newExpandedKeys) => {
    // 这里直接使用AntD返回的新展开keys数组
    setExpandedKeys(newExpandedKeys);
  };

  return (
    <>
      <PageContainer>
        <ProCard split="vertical">
          <ProCard colSpan="20%">
            <Tree
              showIcon
              checkable
              checkStrictly
              treeData={treeData}
              expandedKeys={expandedKeys}
              onSelect={onSelect}
              onRightClick={onRightClick}
              onExpand={handleExpand}
              onCheck={onCheck}
              checkedKeys={checkedKey ? [checkedKey] : []}
            />
          </ProCard>
          <ProCard split="horizontal">
            <ProCard>
              <AddButtonTags values={currentRow || {}}></AddButtonTags>
            </ProCard>
            <ProCard>
              <AddPermForm
                onSubmit={async (value) => {
                  const permissionIds = value?.targetKeys;
                  const menuOrBtnId = currentRow?.id;
                  const success = await handleAdd('/system/rbacPermissionMenuBtn', {
                    permissionIds,
                    menuOrBtnId,
                    correlationType: 1,
                  });

                  if (success) {
                    setCurrentRow(undefined);

                    if (actionRef.current) {
                      await actionRef.current.reload();
                    }
                  }
                }}
                values={currentRow || {}}
              />
            </ProCard>
          </ProCard>
        </ProCard>

        <AddModal
          onSubmit={async (value) => {
            const success = await handleAdd('/system/rbacMenu', value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                await actionRef.current.reload();
              }
            }
          }}
          onCancel={() => handleModalVisible(false)}
          visible={createModalVisible}
          values={currentRow || {}}
        />
        <UpdateModal
          onSubmit={async (values: any) => {
            const success = await handleUpdate('/system/rbacMenu', values, currentRow);
            if (success) {
              handleUpdateModalVisible(false);
              setCurrentRow(undefined);

              if (actionRef.current) {
                await actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
          }}
          updateModalVisible={updateModalVisible}
          values={currentRow || {}}
        />
      </PageContainer>
    </>
  );
};

export default Index;
